package com.ruoyi.manage.enterprise.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.ListUtil;
import com.ruoyi.common.utils.ObjUtil;
import com.ruoyi.common.utils.StrUtil;
import com.ruoyi.common.utils.uuid.NumsUtils;
import com.ruoyi.manage.enterprise.domain.PcProductAccessStandard;
import com.ruoyi.manage.enterprise.domain.PcProductBaseInfo;
import com.ruoyi.manage.enterprise.domain.PcProductExtendInfo;
import com.ruoyi.manage.enterprise.domain.PcProductRefIndustry;
import com.ruoyi.manage.enterprise.mapper.PcProductBaseInfoMapper;
import com.ruoyi.manage.enterprise.service.IPcProductAccessStandardService;
import com.ruoyi.manage.enterprise.service.IPcProductBaseInfoService;
import com.ruoyi.manage.enterprise.service.IPcProductExtendInfoService;
import com.ruoyi.manage.enterprise.service.IPcProductRefIndustryService;
import com.ruoyi.manage.organization.domain.BizOrganization;
import com.ruoyi.manage.organization.service.IBizOrganizationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


/**
 * 产品基本信息Service业务层处理
 *
 * @author ruoyi
 * @date 2025-08-18
 */
@Service
public class PcProductBaseInfoServiceImpl extends ServiceImpl<PcProductBaseInfoMapper, PcProductBaseInfo> implements IPcProductBaseInfoService {

    @Autowired
    IPcProductExtendInfoService iPcProductExtendInfoService;

    @Autowired
    IPcProductAccessStandardService iPcProductAccessStandardService;

    @Autowired
    IPcProductRefIndustryService iPcProductRefIndustryService;

    @Autowired
    IBizOrganizationService iBizOrganizationService;

    @Override
    public PcProductBaseInfo queryGetById(Long id) {
        PcProductBaseInfo pcProductBaseInfo = this.getById(id);
//        插入扩展产品信息表
        PcProductExtendInfo extendInfo = iPcProductExtendInfoService.getOne(new QueryWrapper<PcProductExtendInfo>().eq("product_id", pcProductBaseInfo.getId()));
        pcProductBaseInfo.setExtendInfo(extendInfo);
//        插入产品准入条件
        PcProductAccessStandard standardServiceOne = iPcProductAccessStandardService.getOne(new QueryWrapper<PcProductAccessStandard>().eq("product_id", pcProductBaseInfo.getId()));
        pcProductBaseInfo.setAccessStandard(standardServiceOne);
//      插入行业信息
        List<PcProductRefIndustry> list = iPcProductRefIndustryService.lambdaQuery().eq(PcProductRefIndustry::getProductId, id).list();
        pcProductBaseInfo.setIndustries(list);

        return pcProductBaseInfo;
    }

    /**
     * 新增产品基本信息
     *
     * @param pcProductBaseInfo 产品基本信息
     * @return 结果
     */
    @Override
    @Transactional
    public boolean addPcProductBaseInfo(PcProductBaseInfo pcProductBaseInfo) {
        try {
            pcProductBaseInfo.setProductSerialNumber(NumsUtils.generateCode("C"));
            pcProductBaseInfo.setAuditStatus("0");
            pcProductBaseInfo.setEnabled("0");
            this.save(pcProductBaseInfo);
//        给机构增加产品数量
            String belongInstitution = pcProductBaseInfo.getBelongInstitution();
            // 推荐：原子性自增，高效且线程安全
            if(StrUtil.isNotBlank(belongInstitution)){
                iBizOrganizationService.lambdaUpdate().setSql("product_total = product_total + 1").eq(BizOrganization::getOrgPath, belongInstitution).update();
            }
//        添加产品补充信息
            PcProductExtendInfo extendInfo = pcProductBaseInfo.getExtendInfo();
            extendInfo.setProductId(pcProductBaseInfo.getId());
            iPcProductExtendInfoService.addPcProductExtendInfo(extendInfo);
//         添加准入条件
            PcProductAccessStandard accessStandard = pcProductBaseInfo.getAccessStandard();
            accessStandard.setProductId(pcProductBaseInfo.getId());
            iPcProductAccessStandardService.addPcProductAccessStandard(accessStandard);

//            添加所属行业信息
            List<PcProductRefIndustry> industries = pcProductBaseInfo.getIndustries();
            if (ObjUtil.isNotNull(industries) && industries.size() > 0) {
                industries.forEach(e -> {
                    e.setProductId(pcProductBaseInfo.getId());
                });
                boolean industrys = iPcProductRefIndustryService.saveBatch(industries);
                if (!industrys) {
                    throw new CustomException("保存失败，请重试");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            throw new CustomException("提交失败");
        }
        return true;
    }

    /**
     * 修改产品基本信息
     *
     * @param pcProductBaseInfo 产品基本信息
     * @return 结果
     */
    @Override
    @Transactional
    public boolean updatePcProductBaseInfo(PcProductBaseInfo pcProductBaseInfo) {
        try {
            this.updateById(pcProductBaseInfo);
//           产品扩展表
            PcProductExtendInfo extendInfo = pcProductBaseInfo.getExtendInfo();
            iPcProductExtendInfoService.updateById(extendInfo);
//            产品准入要求
            PcProductAccessStandard accessStandard = pcProductBaseInfo.getAccessStandard();
            iPcProductAccessStandardService.updateById(accessStandard);
//            删除相关行业信息，在增加相关行业
            iPcProductRefIndustryService.remove(new LambdaUpdateWrapper<PcProductRefIndustry>().eq(PcProductRefIndustry::getProductId, pcProductBaseInfo.getId()));
            List<PcProductRefIndustry> industries = pcProductBaseInfo.getIndustries();
            for (PcProductRefIndustry industry : industries) {
                industry.setProductId(pcProductBaseInfo.getId());
            }
            iPcProductRefIndustryService.saveBatch(industries);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("保存失败，请联系管理员");
        }

        return true;
    }

    /**
     * 批量删除产品基本信息
     *
     * @param ids 需要删除的产品基本信息主键
     * @return 结果
     */
    @Override
    public boolean deletePcProductBaseInfoByIds(Long[] ids) {
        return this.removeByIds(ListUtil.toList(ids));
    }

}
